package com.itheima.bos.service.base.impl;

import java.util.List;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.bos.dao.base.ICourierRepository;
import com.itheima.bos.domain.base.Courier;
import com.itheima.bos.service.base.ICourierService;

@Service
@Transactional
public class CourierServiceImpl implements ICourierService {

	// 注入dao
	@Autowired
	private ICourierRepository courierRepository;

	@Override
	public void sava(Courier courier) {
		courierRepository.save(courier);
	}

	@Override
	public Page<Courier> findPageData(Specification<Courier> specification,
			Pageable pageable) {

		return courierRepository.findAll(specification, pageable);
	}

	@Override
	public void deleBacth(String[] idArray) {
		// 遍历id的数组
		for (int i = 0; i < idArray.length; i++) {
			Integer id = Integer.parseInt(idArray[i]);
			courierRepository.updateDelTag(id);
		}
	}

	// 查询未关联的快递员
	@Override
	public List<Courier> findNoassociation() {
		// 封装查询对象
		Specification<Courier> specification = new Specification<Courier>() {

			@Override
			public Predicate toPredicate(Root<Courier> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				//判断关联的地区是否为空
				Predicate p1 = cb.isEmpty(root.get("fixedAreas").as(Set.class));
				return p1;
			}
		};
		return courierRepository.findAll(specification);
	}
}
